package com.kaigejava.quickstart;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by kaigejava on 2019/7/10.
 * 消息消费者
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1:创建一个connectioFactory工厂对象，并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置ip 端口 vhost等
        connectionFactory.setHost("192.168.31.130");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2：通过工厂对象获取到connection对象
        Connection connection = connectionFactory.newConnection();

        //3：公共connection对象获取到一个消息通信的通道 channel
        Channel channel = connection.createChannel();

        //4:声明(创建)一个队列
        String queueName = "mytest001"; //这里可以使用routingKey
        /**
         *  Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
         Map<String, Object> arguments) throws IOException;
         */
        channel.queueDeclare(queueName,true,false,false,null);
        //5:创建消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        //6:设置channel
        //    String basicConsume(String queue, boolean autoAck, Consumer callback) throws IOException;
        /*
        * 参数说明：  queue：队列名称 autoAck：是否自动签收 consumer:消费者对象
         */
        channel.basicConsume(queueName,true,consumer);
        System.out.println("===>>消费者开始处理消息。");
        while(true){
            //7 获取消息
            QueueingConsumer.Delivery delivery =  consumer.nextDelivery();;
            String msg = new String(delivery.getBody());
            System.err.println("消费端: " + msg);
        }
    }
}
